package org.tgcloud.group.service.manager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.tgcloud.group.core.APPResultMessage;
import org.tgcloud.group.core.DateUtil;
import org.tgcloud.group.core.ResultMessage;
import org.tgcloud.group.core.StringUtil;
import org.tgcloud.group.entity.MjMediumOffline;
import org.tgcloud.group.entity.MjMediumOtherProject;
import org.tgcloud.group.entity.MjProjectMedium;
import org.tgcloud.group.repository.MjMediumOfflineMapper;
import org.tgcloud.group.repository.MjMediumOtherProjectMapper;
import org.tgcloud.group.repository.MjProjectMediumMapper;
import org.tgcloud.group.web.controller.dto.medium.AllProjectByYiHuoAndMediumDTO;
import org.tgcloud.group.web.controller.dto.medium.MediumOnlineDTO;
import org.tgcloud.group.web.controller.dto.medium.MjMediumOtherProjectDTO;
import org.tgcloud.group.web.controller.req.medium.MediumUserReq;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author: zhy
 * @Created: 2024-05-29-下午1:18
 * @Description:
 */
@Service
public class MediumOtherProjectManageService {

    @Autowired
    private MjMediumOtherProjectMapper mediumOtherProjectMapper;

    @Autowired
    private MjProjectMediumMapper projectMediumMapper;

    @Autowired
    private MjMediumOfflineMapper mediumOfflineMapper;

    @Autowired
    private ProjectManageService projectManageService;

    public APPResultMessage<Object, MjMediumOtherProjectDTO> getMediumOtherProjectList(Integer pageNum, Integer pageSize, String keyword, Integer otherProjectType) {
        if (pageNum != null && pageSize != null){
            PageHelper.startPage(pageNum, pageSize);
            List<MjMediumOtherProjectDTO> dtos = mediumOtherProjectMapper.selectManageList(keyword,otherProjectType);
            PageInfo<MjMediumOtherProjectDTO> tables = new PageInfo<>(dtos);
            ResultMessage result = ResultMessage.builder().setList(tables.getList()).setAllPageNumber(tables.getPages()).setCount(tables.getTotal());
            APPResultMessage<Object, MjMediumOtherProjectDTO> message = APPResultMessage.getSuccessMessage();
            message.setResult(result);
            return message;
        }else {
            List<MjMediumOtherProjectDTO> dtos = mediumOtherProjectMapper.selectManageList(keyword,otherProjectType);
            ResultMessage result = ResultMessage.builder().setList(dtos);
            APPResultMessage<Object, MjMediumOtherProjectDTO> message = APPResultMessage.getSuccessMessage();
            message.setResult(result);
            return message;
        }
    }

    public APPResultMessage doAddMediumOtherProject(int userId, Integer otherProjectType, String projectName,
                                                    String brands, String remark) {
        MjMediumOtherProject mediumOtherProject = new MjMediumOtherProject();
        mediumOtherProject.setProjectName(projectName);
        mediumOtherProject.setBrands(brands);
        mediumOtherProject.setOtherProjectType(otherProjectType);
        mediumOtherProject.setRemark(remark);
        mediumOtherProject.setStatus((short) 1);
        mediumOtherProject.setCreateUserId(userId);
        mediumOtherProject.setCreateTime(new Date());
        mediumOtherProjectMapper.insertSelective(mediumOtherProject);
        return APPResultMessage.getSuccessMessage();
    }

    public APPResultMessage doEditMediumOtherProject(int userId, Integer otherProjectType, String projectName,
                                                     String brands, int id, String remark) {
        MjMediumOtherProject mediumOtherProject = new MjMediumOtherProject();
        mediumOtherProject.setProjectName(projectName);
        mediumOtherProject.setBrands(brands);
        mediumOtherProject.setOtherProjectType(otherProjectType);
        mediumOtherProject.setRemark(remark);
        mediumOtherProject.setId(id);
        mediumOtherProject.setUpdateTime(new Date());
        mediumOtherProjectMapper.updateByPrimaryKeySelective(mediumOtherProject);
        return APPResultMessage.getSuccessMessage();
    }

    public APPResultMessage doDelMediumOtherProject(int userId, int id) {
        mediumOtherProjectMapper.updateDelStatusById(id);
        return APPResultMessage.getSuccessMessage();
    }

    public APPResultMessage doAddMediumOtherProjectFromCal(int userId, Integer otherProjectType, String projectName, String brands,
                                                           int lineId, Long chooseTime, Integer chooseType, Integer chooseId, Integer sureType,
                                                           String remark, Integer endDayNum, Integer lineIndex, Integer areaType) {
        APPResultMessage appResultMessage = projectManageService.doCheckDateByPackageAndLineIndexAndAreaType(lineId, null, new Date(chooseTime), endDayNum, lineIndex, areaType);
        if (appResultMessage.getKey() != 1000){
            return appResultMessage;
        }
        if (chooseType == null){
            chooseType = 3;
        }
        if(chooseType == 3){
            if (chooseId == null){
                if (StringUtil.isBlank(projectName) || StringUtil.isBlank(brands)){
                    return APPResultMessage.MISS_PARAMETER();
                }
                MjMediumOtherProject mediumOtherProject = new MjMediumOtherProject();
                mediumOtherProject.setProjectName(projectName);
                mediumOtherProject.setBrands(brands);
                mediumOtherProject.setOtherProjectType(otherProjectType);
                mediumOtherProject.setRemark(remark);
                mediumOtherProject.setStatus((short) 1);
                mediumOtherProject.setCreateUserId(userId);
                mediumOtherProject.setCreateTime(new Date());
                mediumOtherProjectMapper.insertSelective(mediumOtherProject);
                chooseId = mediumOtherProject.getId();
            }
        }
        MjProjectMedium projectMedium = new MjProjectMedium();
        projectMedium.setProjectId(chooseId);
        projectMedium.setLineType(chooseType == 3 ? (short) 3 : (short) 2);
        projectMedium.setLineId(lineId);
        projectMedium.setStatus((short) 2);
        projectMedium.setUserId(userId);
        projectMedium.setUpdateTime(new Date());
        projectMedium.setCreateTime(new Date());
        projectMedium.setNum(1);
        projectMedium.setNum2(1);
        projectMedium.setAddIndex(1);
        MjMediumOffline mjMediumOffline = mediumOfflineMapper.selectByPrimaryKey(lineId);
        projectMedium.setCost(mjMediumOffline.getCost());
        projectMedium.setGoodPrice(mjMediumOffline.getGoodPrice());
        projectMedium.setTotalPrice((mjMediumOffline != null && mjMediumOffline.getGoodPrice() != null ? (mjMediumOffline.getGoodPrice()) : BigDecimal.ZERO));
        String putInCycleTypeName = "周";
        int putInCycleNum = 1;
        Integer timeType = 1;
        if (StringUtil.isNotBlank(mjMediumOffline.getPutInCycle())){
            if (mjMediumOffline.getPutInCycle().contains("月")){
                putInCycleTypeName = "月";
                putInCycleNum = Integer.valueOf(mjMediumOffline.getPutInCycle().substring(0,mjMediumOffline.getPutInCycle().indexOf("月")));
                timeType = 2;
            }else if (mjMediumOffline.getPutInCycle().contains("周")){
                putInCycleTypeName = "周";
                putInCycleNum = Integer.valueOf(mjMediumOffline.getPutInCycle().substring(0,mjMediumOffline.getPutInCycle().indexOf("周")));
                timeType = 1;
            }
        }
        Date chooseEndDate = DateUtil.getChooseEndDate(new Date(chooseTime), putInCycleNum, timeType);
        if (endDayNum != null){
            // 如果前端传了结束的天数，结束时间用这个
            chooseEndDate = DateUtil.getEndDate(new Date(chooseTime), endDayNum, 1);
        }
        projectMedium.setChooseTime(new Date(chooseTime));
        projectMedium.setChooseEndTime(chooseEndDate);
        projectMedium.setNum(putInCycleNum);
        projectMedium.setNumTypeName(putInCycleTypeName);
        projectMedium.setSureType(sureType == null ? 2 : sureType);
        projectMedium.setLineIndex(lineIndex);
        projectMedium.setAreaType(areaType);
        projectMediumMapper.insertSelective(projectMedium);
        doAddMediumOtherProjectUpdate(projectMedium.getId(), userId);
        APPResultMessage successMessage = APPResultMessage.getSuccessMessage();
        ResultMessage resultMessage = ResultMessage.builder().setData(projectMedium.getId());
        successMessage.setResult(resultMessage);
        return successMessage;
    }

    public APPResultMessage<Object, AllProjectByYiHuoAndMediumDTO> getAllProjectByYiHuoAndMedium(Integer pageNum, Integer pageSize, String keyword, Integer projectType) {
        if (pageNum != null && pageSize != null){
            PageHelper.startPage(pageNum, pageSize);
            List<AllProjectByYiHuoAndMediumDTO> dtos = mediumOtherProjectMapper.selectAllProjectListByYiHuoAndMedium(keyword,projectType);
            PageInfo<AllProjectByYiHuoAndMediumDTO> tables = new PageInfo<>(dtos);
            ResultMessage result = ResultMessage.builder().setList(tables.getList()).setAllPageNumber(tables.getPages()).setCount(tables.getTotal());
            APPResultMessage<Object, AllProjectByYiHuoAndMediumDTO> message = APPResultMessage.getSuccessMessage();
            message.setResult(result);
            return message;
        }else {
            List<AllProjectByYiHuoAndMediumDTO> dtos = mediumOtherProjectMapper.selectAllProjectListByYiHuoAndMedium(keyword,projectType);
            ResultMessage result = ResultMessage.builder().setList(dtos);
            APPResultMessage<Object, AllProjectByYiHuoAndMediumDTO> message = APPResultMessage.getSuccessMessage();
            message.setResult(result);
            return message;
        }
    }


    public void doAddMediumOtherProjectUpdate(Integer id, Integer userId){
        MjProjectMedium mjProjectMedium = projectMediumMapper.selectByPrimaryKey(id);
        if (mjProjectMedium != null){
            List<JSONObject> jsonList = new ArrayList();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("userId", userId);
            jsonObject.put("time", new Date().getTime());
//            jsonObject.put("dto", mjProjectMedium);
//            if (StringUtil.isNotBlank(mjProjectMedium.getUpdateJson())){
//                jsonList = JSON.parseArray(mjProjectMedium.getUpdateJson(), JSONObject.class);
//            }
            jsonList.add(jsonObject);
            mjProjectMedium.setUpdateJson(JSON.toJSONString(jsonList));
            projectMediumMapper.updateByPrimaryKeySelective(mjProjectMedium);
        }
    }

    public APPResultMessage doSureMediumOtherProject(int userId, Integer chooseId, Integer sureType) {
        projectMediumMapper.updateUserTypeById(chooseId, sureType);
        doAddMediumOtherProjectUpdate(chooseId, userId);
        return APPResultMessage.getSuccessMessage();
    }

    public APPResultMessage doDelProjectMedium(int userId, int id) {
        MjProjectMedium projectMedium = projectMediumMapper.selectByPrimaryKey(id);
        if (userId != 7 && projectMedium != null && !projectMedium.getUserId().equals(userId)){
            return APPResultMessage.getErrorMessage("该项目不允许被其他人删除");
        }
        projectMediumMapper.updateDelById(id);
        return APPResultMessage.getSuccessMessage();
    }

    public APPResultMessage doUpdateMediumUser(int userId, MediumUserReq req) {
        MjProjectMedium projectMedium = projectMediumMapper.selectByPrimaryKey(req.getId());
        if (projectMedium == null){
            return new APPResultMessage(6001, "该排期不存在");
        }
        projectMediumMapper.updateUserIdById(req.getId(), req.getChooseUserId());
        return APPResultMessage.getSuccessMessage();
    }

}
